﻿using AuthCenter.Api.Read.Application.Command.Menu;
using AuthCenter.Api.Read.Application.Output;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using AutoMapper;
using MediatR;

namespace AuthCenter.Api.Read.Application.Hander.Menu
{
    public class GetShowHander : IRequestHandler<GetShowCommand, ApiResult<List<PersonOutput>>>
    {
        private readonly IBaseRepository<MenuModel> _menuRepository;
        private readonly IMapper _mapper;
        public GetShowHander(IBaseRepository<MenuModel> menuRepository, IMapper mapper)
        {
            _menuRepository = menuRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 获取父级菜单
        /// </summary>
        /// <returns></returns>
        public Task<ApiResult<List<PersonOutput>>> Handle(GetShowCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<PersonOutput>> res = new ApiResult<List<PersonOutput>>();
            res.Code = ApiEnums.OK;
            res.Message = "获取成功";
            res.Data = GetTree(0);
            return Task.FromResult(res);
        }
        private List<PersonOutput> GetTree(long id)
        {
            var p = _menuRepository.GetAll().Where(x => x.PId == id);
            var dtos = _mapper.Map<List<PersonOutput>>(p);
            foreach (var d in dtos)
            {
                d.Children = GetTree(d.Id);
            }
            return dtos;
        }
    }
}
